<template>
  <div class="outside-wrap">
    <!-- <router-view></router-view> -->

    <h2 class="titleblue">{{insideGroup ? '内部' : '外部'}}通讯录</h2>
    <div class="contant">
      <div class="plan-operate">
        <div class="btn-block">
          <div class="btn-primary" style="margin-right:10px;" @click="addContact">添加人员</div>
          <div class="btn-primary" @click="addGroup" v-if="showCreateGroupBtn">创建群组</div>
          <el-upload class="upload-demo dutyUpload" :action="$config.FILE_UPLOAD_URL" :data='uploadobj'
                     :show-file-list="false"
                     :on-preview="handlePreview" :before-upload="beforeUpload" :limit="1"
                     accept='.xlsx,.xls,.xlw' :headers="headers"
                     :on-success='uploadSuccess' :on-exceed="handleExceed">
            <el-button class="btn-primary">导入通讯录</el-button>
          </el-upload>
        </div>

        <div class="search-block" v-if="tabIndex === '0'">

          <el-input prefix-icon="el-icon-search" placeholder="联系人姓名" clearable v-model="keyword[0]" @change="searchData"
                    @clear="searchData"
                    class="search-input">
            <div class="btn-primary" slot="append">搜索</div>
          </el-input>
        </div>

        <div class="grouphead fr" v-if="tabIndex === '1'">
          <label>群组搜索</label>
          <el-input prefix-icon="el-icon-search" placeholder="群组名称" v-model="keyword[1]" clearable class="search-input"
                    @change="searchData" @clear="searchData">
            <div class="btn-primary" slot="append">搜索</div>
          </el-input>
        </div>
      </div>
      <el-tabs v-model="tabIndex" type="card" @tab-click="tabClick">
        <el-tab-pane label="通讯录列表" name="0">
          <data-table style="width:100%" :head="tableHead[0]" :data="contactArray" :page="currentPage[0]"
                      :actions="contactActions"
                      @callback="contactAction"></data-table>
        </el-tab-pane>
        <el-tab-pane label="群组列表" name="1">
          <data-table style="width:100%" :head="tableHead[1]" :data="groupArray" :page="currentPage[1]"
                      :actions="groupActions"
                      @callback="groupAction"></data-table>
        </el-tab-pane>
      </el-tabs>

      <div class="block">
        <el-pagination @current-change="handleCurrentChange"
                       :current-page.sync="currentPage[parseInt(tabIndex, 10)]" layout="total,prev, pager, next, jumper"
                       :total="dataCount[parseInt(tabIndex, 10)]" background>
        </el-pagination>
      </div>
    </div>

    <el-dialog
      v-if="dialogType === 'create-contact' && showDialog"
      :visible.sync="showDialog"
      width="80%" append-to-body @close="showDialog = false; contactData = null">
      <create-contact
        :org-array="orgArray"
        @refresh="refreshList(0)"
        :contact-data="contactData"
        @close='showDialog = false'
      />
    </el-dialog>

    <el-dialog
      v-if="dialogType === 'create-group' && showDialog"
      :visible.sync="showDialog"
      width="80%" append-to-body @close="showDialog = false; contactData = null">
      <create-group
        @close='showDialog = false'
        @refresh="refreshList(1)"
      />

    </el-dialog>

    <el-dialog
      v-if="dialogType === 'group-detail' && showDialog"
      :visible.sync="showDialog"
      width="80%" append-to-body @close="showDialog = false; contactData = null">
      <group-detail :groupData='groupData' :mode="groupDetailMode" @refresh='refreshList(1)'
                    @close="showDialog = false"/>

    </el-dialog>
  </div>
</template>

<script>
  import DataTable from '@/components/common/DataTable.vue'
  import GroupDetail from './GroupDetail'
  import CreateGroup from './CreateGroup'
  import CreateContact from './CreateContact'
  import groupService from '@/services/GroupService.js'
  import contactService from '@/services/ContactService.js'
  import * as orgService from '@/services/OrganizationService.js'

  export default {
    components: {
      CreateContact,
      GroupDetail,
      CreateGroup,
      'data-table': DataTable,
      'create-group': CreateGroup,
      'group-detail': GroupDetail,
      'create-contact': CreateContact
    },
    data: function () {
      return {
        tableHead: [
          [
            {name: '姓名', prop: 'name'},
            {name: '管理单位', prop: 'orgName'},
            {name: '所属部门', prop: 'deptName'},
            {name: '联系电话', prop: 'telephone'},
          ],
          [
            {name: '群名称', prop: 'name'},
            {name: '群人数', prop: 'contactCount'},
            {name: '创建时间', prop: 'displayTime'},
            {name: '创建人', prop: 'createUserName'}
          ]
        ],
        dataCount: [0, 0],
        currentPage: [1, 1],
        tabIndex: '0',
        contactArray: [],
        groupArray: [],
        showCreateGroupBtn: false,
        showDialog: false,
        dialogType: null,
        contactData: null,
        groupData: null,
        keyword: ['', ''],
        groupDetailMode: '',
        contactActions: ['edit', 'del'],
        groupActions: ['view'],
        insideGroup: false,
        uploadobj: {
          filename: '值班表',
          mimeType: 'application/vnd.ms-excel',
          bus: 'contact',
        },
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('token')
        }
      }
    },
    created () {
      this.showCreateGroupBtn = this.$checkPermission('/inside-contact/create-group')
      if (this.showCreateGroupBtn) {
        this.groupActions.push('edit')
        this.groupActions.push('del')
      }
      this.getGroupData()
      this.getContactData()
    },
    mounted () {
      // this.$root.eventHub.$on('update1', (res) => {
      //   this.getData()
      // })
    },
    methods: {
      submit: function () {
      },
      contactAction (param) {
        if (param.action === 'edit') {
          this.contactData = param.data
          this.dialogType = 'create-contact'
          this.showDialog = true
        } else if (param.action === 'del') {
          contactService.delete(param.data.id).then(res => {
            this.$message.success('删除成功!')
            this.getContactData()
          })
        }
      },
      refreshList (tab) {
        this.showDialog = false
        tab === 0 ? this.getContactData() : this.getGroupData()
        // if (tab === parseInt(this.tabIndex, 10)) {
        //   tab === 0 ? this.getContactData() : this.getGroupData()
        // }
      },
      groupAction (param) {
        if (param.action === 'edit' || param.action === 'view') {
          this.groupData = param.data
          this.dialogType = 'group-detail'
          this.groupDetailMode = param.action
          this.showDialog = true
        } else if (param.action === 'del') {
          groupService.delete(param.data.id).then(() => {
            this.$message.success('群组删除成功')
            this.getGroupData()
          })
        }
      },
      tabClick (tab, event) {
      },
      handleCurrentChange (page) {
        this.currentPage[parseInt(this.tabIndex, 10)] = page
        if (this.tabIndex === '0') {
          this.getContactData()
        } else {
          this.getGroupData()
        }
      },
      addContact () {
        this.dialogType = 'create-contact'
        this.showDialog = true
      },
      addGroup () {
        this.dialogType = 'create-group'
        this.showDialog = true
      },

      getContactData () {
        // let query = ''
        let query = 'insideGroup==' + (this.insideGroup ? 'true' : 'false')
        if (this.keyword[0]) {
          query += ';name=like=' + this.keyword[0]
        }
        contactService.ps(this.currentPage[0] - 1, query).then(res => {
          this.dataCount[0] = res.dataCount
          this.contactArray = res.data
        })
      },

      getGroupData () {
        let query = 'insideGroup==' + (this.insideGroup ? 'true' : 'false')
        if (this.keyword[1]) {
          query += ';name=like=' + this.keyword[1]
        }
        groupService.ps(this.currentPage[1] - 1, query).then(res => {
          this.dataCount[1] = res.dataCount
          res.data.forEach(d => d.displayTime = this.$m(d.createTime).format('YYYY-MM-DD HH:mm:ss'))
          this.groupArray = res.data
        })
      },
      searchData () {
        this.currentPage[parseInt(this.tabIndex, 10)] = 1
        if (this.tabIndex === '0') {
          this.currentPage[0] = 1
          this.getContactData()
        } else {
          this.currentPage[1] = 1
          this.getGroupData()
        }
      },
      dpChanges () {
        let org = this.orgArray.find(o => o.id === this.orgId)
        if (org && org.sub) this.deptArray = org.sub || []
        this.searchData()
      },
      uploadSuccess (res) {
        contactService.importContact(res.data.realPath, this.insideGroup).then(data => {
          this.$message.success('成功导入' + data.count + '通讯录')
          this.getContactData()
        })
      },
      handlePreview (file) {
      },
      handleExceed (files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      beforeUpload (file) {
        this.uploadobj.filename = file.name
        return true
      }

    }
  }

</script>

<style lang="scss">

  .outside-wrap {
    display: inline-block;
    width: 100%;

    .contant {
      margin-top: 20px;
      padding: 0px 30px;
      box-sizing: border-box;
    }

    .el-tabs--card > .el-tabs__header .el-tabs__nav {
      border: none;
      border-radius: 0;
    }

    .plan-operate {
      display: flex;
      margin-bottom: 20px;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
    }

    .search-block {
      display: flex;
      align-items: center;
    }

    .planselect input {
      width: 122px;
      border-radius: 4px;
      border: solid 1px #dddddd;
    }

    .el-table__header {
      width: 100% !important;
    }

    .has-gutter {
      width: 100% !important;
    }

    .search-input input {
      width: 130px;
      margin-right: 10px;
      border-radius: 0px;
    }

    .search-input .el-input-group__append {
      border-left: 1px;
      width: 56px;
      padding: 0;
      background-color: #0062cd;
      border-radius: 2px;
      font-size: 14px;
      color: #ffffff;
    }

    .el-progress {
      width: 80%;
      float: left;
    }

    .number {
      float: left;
      font-size: 12px;
    }

    .btn-block {
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    .el-select {
      margin: 0px 10px;
      background: #FAFAFA
    }

    .el-table tr:nth-child(2n) {
      background: #FAFAFA
    }

    .el-table td:first-child, .el-table th:first-child {
      width: 100px;
    }

    .dutyUpload {
      width: 130px;
      height: 40px;
      float: left;
      margin-right: 10px;
    }

    .dutyUpload .el-upload--text {
      width: 100%;
      height: 40px;
      float: left;
      border: none;
    }

    .el-input-group {
      width: auto;
    }

  }
</style>
